package com.black.auth.authority;

import com.google.common.collect.Maps;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

import java.util.Map;

/**
 * 共享权限管理器
 *
 * @author linwenfeng
 */
public class ShareAuthenticationManager implements AuthenticationManager {

    private final Map<String, AuthenticationProvider> specialProviderMap = Maps.newHashMap();

    private final AuthenticationProvider defaultAuthenticationProvider;

    private final static String CLIENT_ID = "client_id";

    public ShareAuthenticationManager(AuthenticationProvider defaultAuthenticationProvider) {
        this.defaultAuthenticationProvider = defaultAuthenticationProvider;
    }


    @Override
    @SuppressWarnings("unchecked")
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Object details = authentication.getDetails();
        String clientId = null;
        if (details != null) {
            if (details instanceof Map) {
                Map<String, String> map = (Map<String, String>) details;
                clientId = map.get(CLIENT_ID);
            } else {
                clientId = details.toString();
            }
        }
        AuthenticationProvider authenticationProvider = null;
        //根据不同的client_id调用不同的处理
        if (clientId != null) {
            authenticationProvider = specialProviderMap.get(clientId);
        }

        if (authenticationProvider == null) {
            authenticationProvider = this.defaultAuthenticationProvider;
        }
        return authenticationProvider.authenticate(authentication);
    }

    public void putSpecialProvider(String clientId, AuthenticationProvider provider) {
        this.specialProviderMap.put(clientId, provider);
    }
}
